package com.dm0858.bianmin.utils;

import com.dm0858.bianmin.model.entity.NewsRecord;
import com.dm0858.bianmin.model.entity.NormalListData;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.litepal.crud.DataSupport;

import java.util.List;

/**
 * Created by yelvqing on 2017/11/21.
 */

public class NormalListRecordHelper {

    private static Gson mGson = new Gson();

    /**
     * 获取数据库保存的某个频道的最后一条记录
     *
     * @return
     */
    public static NewsRecord getLastNewsRecord() {
        return DataSupport.findLast(NewsRecord.class);
    }

    /**
     * 获取某个频道上一组新闻记录
     *
     * @param page        页码
     * @return
     */
    public static NewsRecord getPreNewsRecord( int page) {
        List<NewsRecord> newsRecords = selectNewsRecords(page - 1);

        if (ListUtils.isEmpty(newsRecords)) {
            return null;
        }

        return newsRecords.get(0);
    }


    /**
     * 保存新闻记录
     *
     * @param json
     */
    public static void save(String json) {
        int page = 1;
        NewsRecord lastNewsRecord = getLastNewsRecord();
        if (lastNewsRecord != null) {
            //如果有记录
            page = lastNewsRecord.getPage() + 1;//页码为最后一条的页码加1
        }
        //保存新的记录
        NewsRecord newsRecord = new NewsRecord("0", page, json, System.currentTimeMillis());
        newsRecord.saveOrUpdate("page = ?", String.valueOf(page));
    }


    /**
     * 根据频道码和页码查询新闻记录
     * @param page
     * @return
     */
    private static List<NewsRecord> selectNewsRecords(int page) {
        return DataSupport
                .where("page = ?", String.valueOf(page))
                .find(NewsRecord.class);
    }

    /**
     * 将json转换成新闻集合
     *
     * @param json
     * @return
     */
    public static List<NormalListData> convertToNewsList(String json) {
        return mGson.fromJson(json, new TypeToken<List<NormalListData>>() {
        }.getType());
    }
}
